<?php

App::uses('StringUtil', 'Lib');


class GenericUtil {


	 
	public static function recipientsToArray($recipients) {
		if (empty($recipients) ) {
			return null;
		}
		$recipientsArray = explode(",",str_replace(";", ",", preg_replace('/\s+/', '',$recipients)));
		return $recipientsArray;
	}
    
    public static function generate_key($len = 8) { 
     // $salt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
     $salt = Configure::read('Security.salt');
     $cipherSeed = Configure::read('Security.cipherSeed');
	 return substr(str_shuffle($salt.$cipherSeed),0,$len);
    }
	
	public static function soccerhistory($feedid, $controller) {
		GenericUtil::soccerfixtures($feedid, $controller);
	}
	
	public static function soccerfixtures($feedid, $controller) {
		$percentuale=0;
		$controller->loadModel("Feed");
		try {
			$feed=$controller->Feed->read(null,$feedid);		
			$url = $feed["Feed"]["url"];
			$countryCode = $feed["Feed"]["country_code"];
			$sxe = new SimpleXMLElement($url,0,true);
			$controller->loadModel("Match");		
			$controller->loadModel("Event");		
			$controller->loadModel("Substitution");		
			$controller->loadModel("Lineups");		
			$controller->loadModel("Tournament");		
			if ($sxe->tournament->attributes()->league!="Serie B")
				$weeks=$sxe->xpath("/results/tournament/week");
			else
				$weeks=$sxe->xpath("/results/tournament/stage/week");
			if ($weeks) {
				$step= intval(100/count($weeks));
				foreach ($weeks as $week) {
					$tournamentId = null;
					$tournament = $controller->Tournament->find("first",array("recursive"=>-1
													,"conditions"=>array("country"=>$sxe->attributes()->country
																		,"league"=>$sxe->tournament->attributes()->league
																		,"season"=>$sxe->tournament->attributes()->season
																		,"week"=>$week->attributes()->number)));
					if (isset($tournament["Tournament"]["id"]) && !empty($tournament["Tournament"]["id"])) {
						$tournamentId = $tournament["Tournament"]["id"];
						$controller->Tournament->read(null,$tournamentId);
						$controller->Tournament->set("country_code",$countryCode);
						$controller->Tournament->save();
					} else {
						$controller->Tournament->create();
						$controller->Tournament->set("external_id",$sxe->tournament->attributes()->id);
						$controller->Tournament->set("stage_id",$sxe->tournament->attributes()->stage_id);
						$controller->Tournament->set("country",$sxe->attributes()->country);
						$controller->Tournament->set("country_code",$countryCode);
						$controller->Tournament->set("season",$sxe->tournament->attributes()->season);
						$controller->Tournament->set("week",$week->attributes()->number);
						$controller->Tournament->set("league",$sxe->tournament->attributes()->league);
						$controller->Tournament->save();
						$tournamentId = $controller->Tournament->id;
					}
					// pr($tournamentId);die;
					foreach ($week->children() as $match) {
							// pr($match);
							$controller->Match->set("id",$match->attributes()->id);
							$controller->Match->set("fix_id",$match->attributes()->fix_id);
							$controller->Match->set("static_id",$match->attributes()->static_id);
							$controller->Match->set("tournament_id",$tournamentId);
							$datetime = new DateTime($match->attributes()->date);
							$controller->Match->set("date",$datetime->format("Y-m-d"));
							$controller->Match->set("date_string",$match->attributes()->date);
							$controller->Match->set("time",$match->attributes()->time);
							$controller->Match->set("status",$match->attributes()->status);
							$controller->Match->set("localteam",$match->localteam->attributes()->name);
							$controller->Match->set("localteam_id",$match->localteam->attributes()->id);
							$controller->Match->set("visitorteam",$match->visitorteam->attributes()->name);
							$controller->Match->set("visitorteam_id",$match->visitorteam->attributes()->id);
							$controller->Match->set("score_localteam",$match->localteam->attributes()->score);
							$controller->Match->set("score_visitorteam",$match->visitorteam->attributes()->score);
							$controller->Match->save();
							// aggiorno la tabella team
							// pr("fine");die;
							$controller->loadModel("Team");
							$controller->Team->read(null,$match->localteam->attributes()->id);
							if (!isset($controller->Team->data["Team"]["id"]))
								GenericUtil::import_teams(FEED_TEAMS,$match->localteam->attributes()->id,$controller);
							$controller->Team->read(null,$match->visitorteam->attributes()->id);
							if (!isset($controller->Team->data["Team"]["id"]))
								GenericUtil::import_teams(FEED_TEAMS,$match->visitorteam->attributes()->id,$controller);
							
							$controller->Event->deleteAll(array('Event.match_id' => $match->attributes()->id), false);
							foreach ($match->children()->goals as $goals) {
								foreach ($goals as $goal) {
									// pr($goal);die;
									$controller->Event->create();
									$controller->Event->set("type","goal");
									$controller->Event->set("team_type",$goal->attributes()->team);
									$controller->Event->set("team",$match->{$goal->attributes()->team}->attributes()->name);
									$controller->Event->set("minute",$goal->attributes()->minute);
									$controller->Event->set("player",$goal->attributes()->player);
									$controller->Event->set("score",$goal->attributes()->score);
									$controller->Event->set("match_id",$match->attributes()->id);
									$controller->Event->save();
								}
							}
							$controller->Substitution->deleteAll(array('Substitution.match_id' => $match->attributes()->id), false);
							foreach ($match->children()->substitutions->localteam as $substitutions) {
									// pr($substitutions);die;
								foreach ($substitutions as $substitution) {
									$controller->Substitution->create();
									$controller->Substitution->set("player_in_number",$substitution->attributes()->player_in_number);
									$controller->Substitution->set("player_in_name",$substitution->attributes()->player_in_name);
									$controller->Substitution->set("player_in_booking",$substitution->attributes()->player_in_booking);
									$controller->Substitution->set("player_in_id",$substitution->attributes()->player_in_id);
									$controller->Substitution->set("player_out_name",$substitution->attributes()->player_out_name);
									$controller->Substitution->set("player_out_id",$substitution->attributes()->player_out_id);
									$controller->Substitution->set("minute",$substitution->attributes()->minute);
									$controller->Substitution->set("team","localteam");
									$controller->Substitution->set("team_name",$match->{"localteam"}->attributes()->name);
									$controller->Substitution->set("match_id",$match->attributes()->id);
									$controller->Substitution->save();
								}
							}
							foreach ($match->children()->substitutions->visitorteam as $substitutions) {
									// pr($substitutions);die;
								foreach ($substitutions as $substitution) {
									$controller->Substitution->create();
									$controller->Substitution->set("player_in_number",$substitution->attributes()->player_in_number);
									$controller->Substitution->set("player_in_name",$substitution->attributes()->player_in_name);
									$controller->Substitution->set("player_in_booking",$substitution->attributes()->player_in_booking);
									$controller->Substitution->set("player_in_id",$substitution->attributes()->player_in_id);
									$controller->Substitution->set("player_out_name",$substitution->attributes()->player_out_name);
									$controller->Substitution->set("player_out_id",$substitution->attributes()->player_out_id);
									$controller->Substitution->set("minute",$substitution->attributes()->minute);
									$controller->Substitution->set("team","visitorteam");
									$controller->Substitution->set("team_name",$match->{"visitorteam"}->attributes()->name);
									$controller->Substitution->set("match_id",$match->attributes()->id);
									$controller->Substitution->save();
								}
							}
							$controller->Lineups->deleteAll(array('Lineups.match_id' => $match->attributes()->id), false);
							foreach ($match->children()->lineups->localteam as $localteam) {
								foreach ($localteam as $player) {
									// pr($player);die;
									$controller->Lineups->create();
									$controller->Lineups->set("team","localteam");
									$controller->Lineups->set("team_name",$match->{"localteam"}->attributes()->name);
									$controller->Lineups->set("number",$player->attributes()->number);
									$controller->Lineups->set("player_id",$player->attributes()->id);
									$controller->Lineups->set("name",$player->attributes()->name);
									$controller->Lineups->set("match_id",$match->attributes()->id);
									$controller->Lineups->save();
								}
							}
							foreach ($match->children()->lineups->visitorteam as $visitorteam) {
								foreach ($visitorteam as $player) {
									// pr($goal);die;
									$controller->Lineups->create();
									$controller->Lineups->set("team","visitorteam");
									$controller->Lineups->set("team_name",$match->{"visitorteam"}->attributes()->name);
									$controller->Lineups->set("number",$player->attributes()->number);
									$controller->Lineups->set("player_id",$player->attributes()->id);
									$controller->Lineups->set("name",$player->attributes()->name);
									$controller->Lineups->set("match_id",$match->attributes()->id);
									$controller->Lineups->save();
								}
							}
					}
					$percentuale=$percentuale+$step;
					$controller->Feed->set("perc",$percentuale);
					$controller->Feed->set("dt_import",date("Y/m/d H:i:s"));
					$controller->Feed->save();
				}
			}
			$percentuale=100;
			$controller->Feed->set("state",FEED_STATE_IMPORT);
			$controller->Feed->set("error",null);
			$controller->Feed->set("perc",$percentuale);
			$controller->Feed->set("dt_import",date("Y/m/d H:i:s"));
			$controller->Feed->save();
		} catch (Exception $e) {
			// CakeLog::error($e->getMessage(),$e);
			$controller->Feed->set("state",FEED_STATE_ERROR);
			$controller->Feed->set("error",$e->getMessage());
			$controller->Feed->set("perc",$percentuale);
			$controller->Feed->set("dt_import",date("Y/m/d H:i:s"));
			$controller->Feed->save();
			throw $e;
		}
	}

	public static function import_teams($url,$teamId=null,$controller) {
		if (empty($teamId))
			$sxe = new SimpleXMLElement($url,0,true);
		else
			$sxe = new SimpleXMLElement($url."/".$teamId,0,true);
		$controller->loadModel("Team");		
		$controller->Team->set("id",$sxe->team->attributes()->id);
		$controller->Team->set("is_national_team",$sxe->team->attributes()->is_national_team);
		$controller->Team->set("name",$sxe->team->name);
		$controller->Team->set("country",$sxe->team->country);
		$controller->Team->set("founded",$sxe->team->founded);
		$controller->Team->set("venue_name",$sxe->team->venue_name);
		$controller->Team->set("venue_id",$sxe->team->venue_id);
		$controller->Team->set("venue_surface",$sxe->team->venue_surface);
		$controller->Team->set("venue_capacity",$sxe->team->venue_capacity);
		// $controller->Team->set("venue_image",$sxe->team->venue_image);
		$controller->Team->set("image",$sxe->team->image);
		// $controller->Team->set("coach",$sxe->team->coach->attributes()->name);
		$controller->Team->save();
	}

	
}

?>